package com.daisuxia.web.controller;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.daisuxia.allin.SybUtil;
import com.daisuxia.back.utils.SysCacheUtils;
import com.daisuxia.constant.Constant;
import com.daisuxia.web.pojo.BorrowOrder;
import com.daisuxia.web.pojo.Repayment;
import com.daisuxia.web.pojo.RepaymentDetail;
import com.daisuxia.web.pojo.User;
import com.daisuxia.web.service.BorrowOrderService;
import com.daisuxia.web.service.RepaymentDetailService;
import com.daisuxia.web.service.RepaymentService;
import com.daisuxia.web.service.UserService;

import redis.clients.jedis.JedisCluster;

@Controller
@RequestMapping("allinpay")
public class AllinPayNotify {
	
	private static final Logger log = LoggerFactory.getLogger(AllinPayNotify.class);

	@Autowired
	private JedisCluster jedisCluster;
	@Autowired
	private UserService userService;
	@Autowired
	private BorrowOrderService borrowOrderService;
	@Autowired
	private RepaymentService repaymentService;
	@Autowired
	private RepaymentDetailService repaymentDetailService;
	
	@RequestMapping("notify")
	public void allinPayNotify(HttpServletRequest request,HttpServletResponse response) throws IOException {
		request.setCharacterEncoding("UTF-8");//通知传输的编码为UTF-8
		response.setCharacterEncoding("UTF-8");
		TreeMap<String,String> params = getParams(request);//动态遍历获取所有收到的参数,此步非常关键,因为收银宝以后可能会加字段,动态获取可以兼容
		try {
			Map<String,String> allinContants = SysCacheUtils.getConfigParams("ALLIN");
			String currentCust = allinContants.get("CURRENT_CUST_ALLIN");
			boolean isSign = SybUtil.validSign(params, allinContants.get("APPKEY_ALLIN_"+currentCust));// 接受到推送通知,首先验签
			System.out.println("验签结果:"+isSign);
			if(isSign) {
				//验签完毕进行业务处理
				String cusorderid = params.get("cusorderid");//原订单号
				log.info("扫码还款回调：cusorderid="+cusorderid);
				try {
					RepaymentDetail detail = repaymentDetailService.selectByOrderId(cusorderid);
					if(null!=detail && RepaymentDetail.STATUS_WAIT==detail.getStatus()&&"0000".equals(params.get("trxstatus"))) {
						BorrowOrder bo = borrowOrderService.findOneBorrow(detail.getAssetOrderId());
						Map<String, Object> map = new HashMap<String, Object>();
						map.put("assetOrderId", bo.getId());
						Repayment re = repaymentService.findOneRepayment(map);
						User user = userService.searchByUserid(bo.getUserId());
						RepaymentDetail newDetail = new RepaymentDetail();
						newDetail.setId(detail.getId());
						newDetail.setStatus(RepaymentDetail.STATUS_SUC);
						newDetail.setUpdatedAt(new Date());
						log.info("newDetail:"+newDetail.toString());
						if(null != newDetail.getStatus())
							repaymentDetailService.updateByPrimaryKeySelective(newDetail);
						repaymentService.repay(re, detail);
						// 如果是未逾期的还款，调用提额
						if (re.getRepaymentedAmount()>=re.getRepaymentAmount()&&re.getLateDay() == 0) {
							user = userService.searchByUserid(re.getUserId());
							log.info("repay to Mention Money ing ----------------->");
							borrowOrderService.addUserLimit(user);
						}
						//删除redis二维码key
						if(RepaymentDetail.TYPE_ALIPAY_SAO==detail.getRepaymentType())
							jedisCluster.del(Constant.PAY_ALIPAY_SAO_PREFIX+re.getId());
						else if(RepaymentDetail.TYPE_WX_SAO==detail.getRepaymentType())
							jedisCluster.del(Constant.PAY_WX_SAO_PREFIX+re.getId());
					}
					response.getOutputStream().write("success".getBytes());
					response.flushBuffer();
				} catch (Exception e) {
					e.printStackTrace();
					response.getOutputStream().write("flase".getBytes());
					response.flushBuffer();
				}
			}
		} catch (Exception e) {//处理异常
			e.printStackTrace();
		}
	}
	
	/**
	 * 动态遍历获取所有收到的参数,此步非常关键,因为收银宝以后可能会加字段,动态获取可以兼容由于收银宝加字段而引起的签名异常
	 * @param request
	 * @return
	 */
	@SuppressWarnings({ "unchecked" })
	private TreeMap<String, String> getParams(HttpServletRequest request){
		TreeMap<String, String> map = new TreeMap<String, String>();
		Map<String,String[]> reqMap = request.getParameterMap();
		for(Object key:reqMap.keySet()){
			String value = ((String[])reqMap.get(key))[0];
			System.out.println(key+";"+value);
			map.put(key.toString(),value);
		}
		return map;
	}
}
